<?php
/**
 * Created by PhpStorm.
 * User: acker
 * Date: 21-06-08
 * Time: 下午6:25
 */

namespace App\Models\yb;
use App\Models\AdminUserModel;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Encore\Admin\Traits\DefaultDatetimeFormat;
use EasyWeChat\Factory;


class NetworkGoodsOrderModel extends Model
{
    use DefaultDatetimeFormat;

    use SoftDeletes;

    /**
     *
     * 表名
     * @var string
     */
    protected $table = 'yb_network_goods_order';

    /**
     * 主键
     *
     * @var string
     */
    protected $primaryKey = 'id';



    /**
     * 该模型是否被自动维护时间戳
     *
     * @var bool
     */
    public $timestamps = true;


    /**
     * 主键
     *
     * @var string
     */
    protected $appends = ['action_id'];

    /**
     * @return mixed
     */
    public function getActionIdAttribute(){
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function Goods()
    {
        return $this->hasOne(GoodsModel::class,'id','goods_id');
    }

    public function getGoodsListAttribute($value)
    {
        return array_values(json_decode($value, true) ?: []);
    }

    public function setGoodsListAttribute($value)
    {
        $this->attributes['goods_list'] = json_encode(array_values($value));
    }

    /**
     * @return mixed
     */
    public function Network()
    {
        return $this->hasOne(AdminUserModel::class,'id','network_id');
    }
    
      public static function getConfig()
    {
        return [
            // 必要配置
            'app_id' =>  env('NETWORK_WECHAT_CLIENT_APP_ID'),
            'mch_id' => env('WECHAT_MCH_ID'),
            'key' =>  env('WECHAT_KEY'),   // API 密钥
        ];
    }

    public static function getRefundConfig()
    {
        return [
            // 必要配置
            'app_id'             => env('NETWORK_WECHAT_CLIENT_APP_ID'),
            'mch_id'             => env('WECHAT_MCH_ID'),
            'key'                => env('WECHAT_KEY'),   // API 密钥

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => base_path('public/cert/apiclient_cert.pem'), // XXX: 绝对路径！！！！
            'key_path'           => base_path('public/cert/apiclient_key.pem'),     // XXX: 绝对路径！！！！
            'notify_url'         => env('APP_URL').'api/network/loading/order/refund/notify',     // 你也可以在下单时单独设置来想覆盖它
        ];
    }

    public static function payByWeChat($orderSn, $openid, $amount)
    {

        $payment = Factory::payment(self::getConfig());

        $jssdk = $payment->jssdk;

        $result = $payment->order->unify([
            'body' => env('APP_NAME'),         // 订单说明
            'out_trade_no' => $orderSn,   // 平台内部订单号
            'total_fee' => $amount * 100,   // 价格, 单位为分
            'notify_url' => env('APP_URL').'api/network/loading/order/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI',
            'openid' => $openid,
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $prepayId = $result['prepay_id'];

            $config = $jssdk->sdkConfig($prepayId);

            return $config;
        }

        if ($result['return_code'] == 'FAIL' && array_key_exists('return_msg', $result)) {
            throw new \Exception($result['return_msg']);
        }

        throw new \Exception($result['err_code_des']);
    }

    
}
